package com.jsh.erp.config;


import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.jsh.common.api.response.QueryResponseResult;
import com.jsh.common.system.vo.LoginUser;
import com.jsh.common.util.RedisUtil;
import com.jsh.config.exception.ExceptionCast;
import com.jsh.erp.constants.RedisConstant;
import com.jsh.erp.datasource.entities.SysUser;
import lombok.SneakyThrows;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.SecurityUtils;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;

/**
 * @Author JiangYaoFeng
 * 2022/1/10 10:51
 */
@Component
public class CustomTenantLineHandler implements TenantLineHandler {


    @Autowired
    RestTemplate restTemplate;

    @Value("${URL.LoginUrl}")
    String loginUrl;
    @Value("${URL.getLoginUserUrl}")
    String getLoginUserUrl;
    @Value("${URL.getUserById}")
    String GetUserById;
    @Value("${clientId}")
    private String clientId;
    @Value("${clientSecret}")
    private String clientSecret;
    @Value("${URL.getRoleList}")
    String getRoleList;
    @Value("${URL.getUserRole}")
    String getUserRole;


    private final String SYSUSER_CACHE="GET_USER_BY_ID";

    @Autowired
    RedisUtil redisUtil;
    @Override
    public Expression getTenantId() {
        LoginUser principal = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Object o = redisUtil.get(RedisConstant.SYSUSER_CACHE + principal.getId());

        if(o!=null){
            SysUser sysUser = (SysUser) o;
            return new LongValue(sysUser.getRelTenantIds());
        }


        SysUser sysUser = GetUserById(principal.getId());
        return new LongValue(sysUser.getRelTenantIds());
    }

    @Override
    public String getTenantIdColumn() {


        return "tenant_id";
    }

    @Override
    public boolean ignoreTable(String tableName) {
        //获取开启状态
        Boolean res = true;
        LoginUser principal = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (principal == null) {
            return true;
        }
            // 这里可以判断是否过滤表
            if ("jsh_material_property".equals(tableName) || "jsh_sequence".equals(tableName)
                    || "jsh_user_business".equals(tableName) || "jsh_function".equals(tableName)
                    || "jsh_platform_config".equals(tableName) || "jsh_tenant".equals(tableName)
                    ||"jsh_role".equals(tableName) ||tableName.contains("sys")||tableName.contains("act")) {
                res = true;
            } else {
                SysUser sysUser;
                Object o = redisUtil.get(SYSUSER_CACHE + principal.getId());
                if(o!=null){
                    sysUser=(SysUser) o;
                }else {
                    sysUser= GetUserById(principal.getId());
                }
                if (sysUser.getRelTenantIds() == null) {
                    return true;
                }


                boolean admin = SecurityUtils.getSubject().hasRole("admin");

                if(admin){
                    return true;
                }
                res = false;




            }


        return res;
    }


    @SneakyThrows
    SysUser GetUserById(String id) {

        String LoginUserUrl = GetUserById + "/" + id + "?clientId=" + clientId + "&clientSecret=" + clientSecret;
        //调用第三方获取用户信息
        QueryResponseResult sysUserResult = restTemplate.getForObject(LoginUserUrl, QueryResponseResult.class);

        if (!sysUserResult.isSuccess()) {
            ExceptionCast.cast(false, 9999, sysUserResult.getMessage());
        }


        HashMap hashMap = (HashMap) sysUserResult.getObject();
        SysUser sysUser = new SysUser();
//            BeanUtils.populate(sysUser,hashMap);

        Class<? extends SysUser> aClass = sysUser.getClass();
        BeanInfo beanInfo = Introspector.getBeanInfo(aClass);
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

        for (PropertyDescriptor prop : propertyDescriptors) {
            String key = prop.getName();
            Class<? extends PropertyDescriptor> aClass1 = prop.getClass();
            if (hashMap.containsKey(key) && hashMap.get(key) != null) {
                Object value = hashMap.get(key);
                Method setMethod = prop.getWriteMethod();
                Class<?> propertyType = prop.getPropertyType();
                if (propertyType.equals(Date.class)) {
                    String[] pattern = new String[]{"yyyy-MM", "yyyyMM", "yyyy/MM", "yyyyMMdd", "yyyy-MM-dd", "yyyy/MM/dd", "yyyyMMddHHmmss", "yyyyMMdd HHmmss", "yyyy-MM-dd HH:mm:ss", "yyyy/MM/dd HH:mm:ss"};
                    Date date = DateUtils.parseDate(value.toString(), pattern);
                    setMethod.invoke(sysUser, date);
                } else {
                    setMethod.invoke(sysUser, value);
                }
            }
        }
        redisUtil.set(SYSUSER_CACHE+id,sysUser,1000*60*60*24);
        return sysUser;

    }


}
